import pattern_util from "./getSearchPattern";
import glossary from "./glossary";
import nodejieba  from "nodejieba";
import indexesSchema from "../models/indexesModel"
import {result_by_BM25 , comprehension_result } from "../util/result_by_BM25"
import searchSchema from "../models/searchModel"
export default class SearchByIntelligence{
  //里面对应的函数
  choose(req,res) {
    let {searchTime,keyword,pageNum,pageSize} = req.query;
    let reg_pattern = new pattern_util();
    let time_pattern = reg_pattern.getTimePattern(searchTime);
    if(time_pattern=="none"){
      res.status(500).send({data:{},msg:glossary.badRequest})
      return;
    }
    time_pattern = RegExp(time_pattern)
    let keys = nodejieba.cut(keyword)
    let condition = []
    for (let i =0;i<keys.length;i++){
      condition.push({key: keys[i]})
    }
    searchSchema.count({},(err1,total)=>{
      if(err1){
        res.status(500).send({data:{},msg:glossary.internalError})
      }else {
        indexesSchema.find({$or: condition}, (err2, doc) => {
          if (err2) {
            res.status(500).send({data: {}, msg: glossary.internalError})
          } else {
            let object = {};
            for (let i = 0; i < doc.length; i++) {
              object[`${doc[i]["key"]}`] = doc[i]["frequency"]
            }
            let result = result_by_BM25(keys, object, total)
            searchSchema.find({date:time_pattern}).and({_id: {$in: result["keys"]}}).exec((err3, info) => {
              if (err3) {
                res.status(500).send({data: {}, msg: glossary.internalError})
              }
              if(info.length===0){
                res.json({data:{result: {},total:0},msg:glossary.success})
                return;
              }
              let array = comprehension_result(result["result"], info, pageNum, pageSize)
              let keys = [];
              for (let i =0;i<array.length;i++) {
                keys.push(array[i]["doc_id"])
              }
              searchSchema.find({_id: {$in:keys}}, (err4,finallyResult)=>{
                if(err4) {
                  res.status(500).send({data: {}, msg: glossary.internalError})
                }else{
                  res.json({data:{result:finallyResult,total:result["keys"].length},msg:glossary.success})
                }
              })
            })
          }
        })
      }
    })
  }
}


